package com.daoshu.mds.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.component.exception.BusinessException;
import com.daoshu.mds.constants.LinkType;
import com.daoshu.mds.system.mapper.GeneralConcatsMapper;
import com.daoshu.mds.system.service.IGeneralConcatsService;
import com.daoshu.mds.system.service.IOConcatsService;
import com.daoshu.mds.system.service.IPConcatsService;
import com.daoshu.system.bo.AccountBo;
import com.daoshu.system.bo.ContentBO;
import com.daoshu.system.bo.DutyBO;
import com.daoshu.system.entity.*;
import com.daoshu.system.qo.GeneralConcatsQO;
import com.daoshu.system.service.OrgFeignService;
import com.daoshu.system.service.PersonFeignService;
import com.daoshu.system.service.PersonOrgFeignService;
import com.daoshu.system.utils.RequestUtils;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  常用联系人服务实现类
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-10
 */
@Service
public class GeneralConcatsServiceImpl extends ServiceImpl<GeneralConcatsMapper, GeneralConcatsEntity> implements IGeneralConcatsService {

	@Autowired private IPConcatsService pConcatsService;
	@Autowired private IOConcatsService oConcatsService;
	@Autowired private OrgFeignService orgService;
	@Autowired private RequestUtils userUtil;
	
	@Override
	public IPage<ContentBO> queryGeneralConcats(GeneralConcatsQO qo) {
		AccountBo user = userUtil.getCurrentUser();
		GeneralConcatsEntity entity = new GeneralConcatsEntity();
		BeanUtils.copyProperties(qo, entity);
		entity.setPersonId(user.getPersonBo().getId());
		QueryWrapper<GeneralConcatsEntity> queryWrapper = new QueryWrapper<>(entity);
		// 查询常用联系人
		IPage<GeneralConcatsEntity> page = this.page(new Page<>(qo.getStart(),qo.getSize()), queryWrapper);
		List<GeneralConcatsEntity> concats = Optional.ofNullable(page.getRecords()).orElse(new ArrayList<GeneralConcatsEntity>());
		List<String> personIds = new ArrayList<>();
		concats.stream().filter(a->a.getLinkType()!=null&&a.getLinkType().equals(LinkType.PERSON.getStatus())).forEach(a->personIds.add(a.getLinkPersonId()));
		IPage<ContentBO> result = new Page<>(qo.getStart(), qo.getSize());
		result.setRecords(pConcatsService.queryPersonConcat(personIds));
		List<String> orgIds = new ArrayList<>();
		concats.stream().filter(a->a.getLinkType()!=null&&a.getLinkType().equals(LinkType.ORG.getStatus())).forEach(a->orgIds.add(a.getLinkPersonId()));
		List<ContentBO> orgContents = Optional.ofNullable(oConcatsService.queryOrgConcat(orgIds)).orElse(new ArrayList<>());
		orgContents.forEach(org->org.setName(org.getOrgName()));
		orgContents.addAll(result.getRecords());
		orgContents.forEach(a->a.setIsGeneralconcat(true));
		result.setRecords(orgContents);
		result.setTotal(page.getTotal());
		return result;
	}

	@Override
	public void addGeneralConcats(GeneralConcatsEntity entity) {
		if(entity==null) {
			throw new BusinessException(500, "常用联系人参数不正确，请确认");
		}
		AccountBo user = userUtil.getCurrentUser();
		entity.setPersonId(user.getPersonBo().getId());
		GeneralConcatsEntity qo = new GeneralConcatsEntity();
		qo.setPersonId(user.getPersonBo().getId());
		GeneralConcatsEntity temp = Optional.ofNullable(this.getOne(new QueryWrapper<GeneralConcatsEntity>(qo).orderByDesc("sort_"))).orElse(new GeneralConcatsEntity());
		int sort = temp.getSort()==null?1:temp.getSort()+1;
		entity.setSort(sort);
		qo.setLinkPersonId(entity.getLinkPersonId());
		GeneralConcatsEntity general = this.getOne(new QueryWrapper<GeneralConcatsEntity>(qo));
		if(general!=null) {
			throw new BusinessException(500, "已有此常用联系人，请不要重复添加");
		}
		this.save(entity);
	}
	
	@Override
	public void batchAddGeneralConcats(List<GeneralConcatsEntity> entitys) {
		if (Collections.isEmpty(entitys)) {
			throw new BusinessException(500, "常用联系人参数不正确，请确认");
		}
		AccountBo user = userUtil.getCurrentUser();
		Set<String> ids = new HashSet<String>();
		entitys.forEach(entity -> { entity.setPersonId(user.getPersonId()); ids.add(entity.getLinkPersonId()); entity.setSort(entitys.indexOf(entity));});
		if(!Collections.isEmpty(this.list(new QueryWrapper<GeneralConcatsEntity>().lambda().eq(GeneralConcatsEntity::getPersonId, user.getPersonId()).in(GeneralConcatsEntity::getLinkPersonId, ids)))) {
			// 如果不为空，那就给前端返回一个500异常
			throw new BusinessException(500, "常用联系人有重复添加，请不要重复添加");
		}
		this.remove(new QueryWrapper<GeneralConcatsEntity>().in("link_person_id_", ids));
		this.saveBatch(entitys);
	}

//	private void updateGeneralConcats(List<GeneralConcatsEntity> entitys) {
//		if(entitys==null||entitys.isEmpty())
//			return;
//		this.saveOrUpdateBatch(entitys);
//	}
	@Autowired private PersonOrgFeignService opService;
	@Autowired private PersonFeignService personService;
	@Override
	public DutyBO queryOrgDuty(String orgId) {
		OrganizationEntity org = Optional.ofNullable(orgService.getById(orgId)).orElse(new OrganizationEntity());
		DutyBO bo = new DutyBO();
		BeanUtils.copyProperties(org, bo);
		// 查询序号最小的默认联系方式
		OConcatsEntity concat = Optional.ofNullable(oConcatsService.getOne(new QueryWrapper<OConcatsEntity>().eq("organization_id_", orgId).eq("default_", 1).orderByAsc("sort_"))).orElse(new OConcatsEntity());
		bo.setConcatPhone(concat.getConcatNumber());
		// 查询单位下面的人与号码，后面要与值守系统对接
		OrganizationPersonEntity op = Optional.ofNullable(opService.getOneByOrgId(orgId)).orElse(new OrganizationPersonEntity());
		PersonEntity person = Optional.ofNullable(personService.getById(op.getPersonId())).orElse(new PersonEntity());
		bo.setDutyPersonName(person.getName());
		bo.setDutyTel(person.getPhone());
		return bo;
	}
}
